<template>
  <div id="contestDetailView">
    <a-row :gutter="[16, 16]">
      <!-- 比赛信息卡片 -->
      <a-col :span="24">
        <a-card v-if="contest">
          <template #title>
            <a-space>
              <a-icon-trophy style="color: #ffd700" />
              <span>{{ contest.title }}</span>
              <a-tag :color="getStatusColor(contest.status)">
                {{ getStatusText(contest.status) }}
              </a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-space>
              <a-button
                v-if="!contest.isRegistered && contest.status !== 2"
                type="primary"
                @click="registerContest"
              >
                报名参赛
              </a-button>
              <a-button
                v-if="contest.isRegistered && contest.status === 1"
                type="success"
                @click="enterContest"
              >
                进入比赛
              </a-button>
              <a-button v-if="isAdmin" type="outline" @click="editContest">
                编辑比赛
              </a-button>
            </a-space>
          </template>

          <a-descriptions :column="{ xs: 1, md: 2, lg: 3 }">
            <a-descriptions-item label="开始时间">
              {{ formatDateTime(contest.startTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="结束时间">
              {{ formatDateTime(contest.endTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="比赛时长">
              {{ getContestDuration(contest) }}
            </a-descriptions-item>
            <a-descriptions-item label="题目数量">
              {{ contest.problems?.length || 0 }} 题
            </a-descriptions-item>
            <a-descriptions-item label="比赛类型">
              {{ contest.ruleType === 0 ? "ACM" : "OI" }}
            </a-descriptions-item>
            <a-descriptions-item label="访问权限">
              <a-tag :color="contest.isPublic ? 'green' : 'orange'">
                {{ contest.isPublic ? "公开" : "私有" }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>

          <div v-if="contest.description" style="margin-top: 16px">
            <h4>比赛描述</h4>
            <p>{{ contest.description }}</p>
          </div>
        </a-card>
      </a-col>

      <!-- 比赛内容标签页 -->
      <a-col :span="24">
        <a-tabs default-active-key="problems">
          <!-- 题目列表 -->
          <a-tab-pane key="problems" title="题目列表">
            <a-table
              :columns="problemColumns"
              :data="contest?.problems || []"
              :pagination="false"
              @row-click="viewProblem"
            >
              <template #status="{ record }">
                <a-tag v-if="record.solved" color="green">已解决</a-tag>
                <a-tag v-else-if="record.attempted" color="orange"
                  >已尝试</a-tag
                >
                <a-tag v-else color="default">未尝试</a-tag>
              </template>
              <template #score="{ record }">
                <span>{{ record.score }} 分</span>
              </template>
            </a-table>
          </a-tab-pane>

          <!-- 排名 -->
          <a-tab-pane key="ranking" title="排名">
            <a-table
              :columns="rankingColumns"
              :data="rankingList"
              :pagination="{
                showTotal: true,
                pageSize: rankingPageSize,
                current: rankingPage,
                total: rankingTotal,
              }"
              @page-change="onRankingPageChange"
            >
              <template #rank="{ record }">
                <a-tag
                  :color="getRankColor(record.rank)"
                  style="font-weight: bold"
                >
                  {{ record.rank }}
                </a-tag>
              </template>
              <template #score="{ record }">
                <span style="font-weight: bold; color: #1890ff">
                  {{ record.totalScore }}
                </span>
              </template>
            </a-table>
          </a-tab-pane>

          <!-- 提交记录 -->
          <a-tab-pane key="submissions" title="提交记录">
            <a-table
              :columns="submissionColumns"
              :data="submissionList"
              :pagination="{
                showTotal: true,
                pageSize: submissionPageSize,
                current: submissionPage,
                total: submissionTotal,
              }"
              @page-change="onSubmissionPageChange"
            >
              <template #result="{ record }">
                <a-tag :color="getResultColor(record.judgeResult)">
                  {{ record.judgeResult }}
                </a-tag>
              </template>
              <template #time="{ record }">
                {{ formatDateTime(record.submitTime) }}
              </template>
            </a-table>
          </a-tab-pane>

          <!-- 公告 -->
          <a-tab-pane key="announcements" title="公告">
            <div v-if="isAdmin" style="margin-bottom: 16px">
              <a-button type="primary" @click="showAnnouncementModal">
                发布公告
              </a-button>
            </div>
            <a-list :data="announcementList" item-layout="vertical">
              <template #item="{ item }">
                <a-list-item>
                  <template #meta>
                    <a-space>
                      <a-tag v-if="item.isImportant" color="red">重要</a-tag>
                      <span>{{ formatDateTime(item.createTime) }}</span>
                    </a-space>
                  </template>
                  <template #title>
                    <a-space>
                      <a-icon-notification />
                      <span>{{ item.title }}</span>
                    </a-space>
                  </template>
                  <template #content>
                    <div v-html="item.content"></div>
                  </template>
                  <template #actions>
                    <a-space v-if="isAdmin">
                      <a-button size="small" @click="editAnnouncement(item)">
                        编辑
                      </a-button>
                      <a-button
                        size="small"
                        status="danger"
                        @click="deleteAnnouncement(item.id)"
                      >
                        删除
                      </a-button>
                    </a-space>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>

    <!-- 公告对话框 -->
    <a-modal
      v-model:visible="announcementModalVisible"
      :title="editingAnnouncement ? '编辑公告' : '发布公告'"
      width="600px"
      @ok="handleAnnouncementSubmit"
      @cancel="announcementModalVisible = false"
    >
      <a-form :model="announcementForm" layout="vertical">
        <a-form-item label="标题" required>
          <a-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
          />
        </a-form-item>
        <a-form-item label="内容" required>
          <a-textarea
            v-model="announcementForm.content"
            placeholder="请输入公告内容"
            :rows="6"
          />
        </a-form-item>
        <a-form-item>
          <a-checkbox v-model="announcementForm.isImportant">
            标记为重要公告
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { ContestControllerService } from "../../generated";
import type {
  Contest,
  ContestProblem,
  ContestSubmission,
  ContestRanking,
  ContestAnnouncement,
} from "../../generated";

const route = useRoute();
const router = useRouter();
const store = useStore();

// 数据
const contest = ref<Contest>();
const rankingList = ref<ContestRanking[]>([]);
const submissionList = ref<ContestSubmission[]>([]);
const announcementList = ref<ContestAnnouncement[]>([]);

// 分页参数
const rankingPage = ref(1);
const rankingPageSize = ref(20);
const rankingTotal = ref(0);
const submissionPage = ref(1);
const submissionPageSize = ref(20);
const submissionTotal = ref(0);

// 公告相关
const announcementModalVisible = ref(false);
const editingAnnouncement = ref<ContestAnnouncement | null>(null);
const announcementForm = ref({
  title: "",
  content: "",
  isImportant: false,
});

// 计算属性
const isAdmin = computed(() => {
  return store.state.user?.loginUser?.userRole === "admin";
});

const contestId = computed(() => route.params.id as string);

// 表格列定义
const problemColumns = [
  {
    title: "题号",
    dataIndex: "displayId",
    width: 80,
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "状态",
    slotName: "status",
    width: 100,
  },
  {
    title: "分值",
    slotName: "score",
    width: 80,
  },
];

const rankingColumns = [
  {
    title: "排名",
    slotName: "rank",
    width: 80,
  },
  {
    title: "用户名",
    dataIndex: "username",
  },
  {
    title: "总分",
    slotName: "score",
    width: 100,
  },
  {
    title: "解题数",
    dataIndex: "solvedCount",
    width: 100,
  },
  {
    title: "罚时",
    dataIndex: "totalPenalty",
    width: 100,
  },
];

const submissionColumns = [
  {
    title: "提交时间",
    slotName: "time",
    width: 180,
  },
  {
    title: "题号",
    dataIndex: "displayId",
    width: 80,
  },
  {
    title: "用户名",
    dataIndex: "username",
  },
  {
    title: "结果",
    slotName: "result",
    width: 100,
  },
];

// 加载比赛详情
const loadContestDetail = async () => {
  try {
    const res = await ContestControllerService.getContestDetailUsingGet(
      parseInt(contestId.value)
    );
    if (res.code === 0) {
      contest.value = res.data;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("加载失败");
  }
};

// 加载排名
const loadRanking = async () => {
  try {
    const res = await ContestControllerService.getContestRankingUsingGet(
      parseInt(contestId.value),
      rankingPage.value,
      rankingPageSize.value
    );
    if (res.code === 0) {
      rankingList.value = res.data || [];
      rankingTotal.value = res.data?.length || 0;
    }
  } catch (error) {
    message.error("加载排名失败");
  }
};

// 加载提交记录
const loadSubmissions = async () => {
  try {
    const res = await ContestControllerService.getContestSubmissionsUsingGet(
      parseInt(contestId.value),
      submissionPage.value,
      submissionPageSize.value
    );
    if (res.code === 0) {
      submissionList.value = res.data.records || [];
      submissionTotal.value = res.data.total || 0;
    }
  } catch (error) {
    message.error("加载提交记录失败");
  }
};

// 加载公告
const loadAnnouncements = async () => {
  try {
    const res = await ContestControllerService.getContestAnnouncementsUsingGet(
      parseInt(contestId.value)
    );
    if (res.code === 0) {
      announcementList.value = res.data || [];
    }
  } catch (error) {
    message.error("加载公告失败");
  }
};

// 分页处理
const onRankingPageChange = (page: number) => {
  rankingPage.value = page;
  loadRanking();
};

const onSubmissionPageChange = (page: number) => {
  submissionPage.value = page;
  loadSubmissions();
};

// 状态处理
const getStatusText = (status: number) => {
  const statusMap = {
    0: "未开始",
    1: "进行中",
    2: "已结束",
  };
  return statusMap[status as keyof typeof statusMap] || "未知";
};

const getStatusColor = (status: number) => {
  const colorMap = {
    0: "blue",
    1: "green",
    2: "gray",
  };
  return colorMap[status as keyof typeof colorMap] || "default";
};

const getRankColor = (rank: number) => {
  if (rank === 1) return "gold";
  if (rank === 2) return "silver";
  if (rank === 3) return "bronze";
  return "default";
};

const getResultColor = (result: string) => {
  const colorMap: Record<string, string> = {
    AC: "green",
    WA: "red",
    TLE: "orange",
    MLE: "purple",
    RE: "red",
    CE: "gray",
  };
  return colorMap[result] || "default";
};

// 时间格式化
const formatDateTime = (time: string) => {
  return moment(time).format("YYYY-MM-DD HH:mm:ss");
};

const getContestDuration = (contest: Contest) => {
  const start = moment(contest.startTime);
  const end = moment(contest.endTime);
  const duration = moment.duration(end.diff(start));
  const hours = Math.floor(duration.asHours());
  const minutes = duration.minutes();
  return `${hours}小时${minutes}分钟`;
};

// 操作处理
const registerContest = async () => {
  try {
    const res = await ContestControllerService.registerContestUsingPost(
      parseInt(contestId.value)
    );
    if (res.code === 0) {
      message.success("报名成功");
      loadContestDetail();
    } else {
      message.error("报名失败，" + res.message);
    }
  } catch (error) {
    message.error("报名失败");
  }
};

const enterContest = () => {
  router.push({
    path: `/contest/${contestId.value}/problems`,
  });
};

const editContest = () => {
  router.push({
    path: `/contest/${contestId.value}/edit`,
  });
};

const viewProblem = (problem: ContestProblem) => {
  router.push({
    path: `/contest/${contestId.value}/problem/${problem.id}`,
  });
};

// 公告处理
const showAnnouncementModal = () => {
  editingAnnouncement.value = null;
  announcementForm.value = {
    title: "",
    content: "",
    isImportant: false,
  };
  announcementModalVisible.value = true;
};

const editAnnouncement = (announcement: ContestAnnouncement) => {
  editingAnnouncement.value = announcement;
  announcementForm.value = {
    title: announcement.title || "",
    content: announcement.content || "",
    isImportant: announcement.isImportant || false,
  };
  announcementModalVisible.value = true;
};

const handleAnnouncementSubmit = async () => {
  try {
    const announcementData = {
      ...announcementForm.value,
      contestId: parseInt(contestId.value),
    };

    let res;
    if (editingAnnouncement.value) {
      res = await ContestControllerService.updateContestAnnouncementUsingPut(
        parseInt(contestId.value),
        editingAnnouncement.value.id!,
        announcementData
      );
    } else {
      res = await ContestControllerService.addContestAnnouncementUsingPost(
        parseInt(contestId.value),
        announcementData
      );
    }

    if (res.code === 0) {
      message.success(editingAnnouncement.value ? "更新成功" : "发布成功");
      announcementModalVisible.value = false;
      loadAnnouncements();
    } else {
      message.error("操作失败，" + res.message);
    }
  } catch (error) {
    message.error("操作失败");
  }
};

const deleteAnnouncement = async (id: number) => {
  try {
    const res =
      await ContestControllerService.deleteContestAnnouncementUsingDelete(
        parseInt(contestId.value),
        id
      );
    if (res.code === 0) {
      message.success("删除成功");
      loadAnnouncements();
    } else {
      message.error("删除失败，" + res.message);
    }
  } catch (error) {
    message.error("删除失败");
  }
};

// 页面加载
onMounted(() => {
  loadContestDetail();
  loadRanking();
  loadSubmissions();
  loadAnnouncements();
});
</script>

<style scoped>
#contestDetailView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 16px;
}

.contest-info {
  margin-bottom: 16px;
}

.contest-description {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</style>
